package com.xiaotou.weibo.impl;

import java.util.ArrayList;
import java.util.List;

import weibo4j.Status;
import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;

import com.xiaotou.weibo.WeiboClient;
import com.xiaotou.weibo.WeiboClientException;
import com.xiaotou.weibo.WeiboStatus;
import com.xiaotou.weibo.WeiboUser;

public class SinaWeiboClient implements WeiboClient {

    private Weibo weibo;

    public SinaWeiboClient(Weibo weibo) {
        this.weibo = weibo;
    }

    @Override
    public List<WeiboUser> getFollows(String id) throws WeiboClientException {
        try {
            final List<WeiboUser> users = new ArrayList<WeiboUser>();
            final List<User> followersStatuses = weibo.getFollowersStatuses(id);
            for (final User user : followersStatuses) {
                users.add(new SinaWeiboUser(user));
            }
            return users;
        } catch (WeiboException e) {
            throw new WeiboClientException(e.getMessage(), e);
        }
    }

    @Override
    public List<WeiboStatus> getPublicTimeline() throws WeiboClientException {
        try {
            final List<WeiboStatus> weiboStatus = new ArrayList<WeiboStatus>();
            final List<Status> publicTimeline = this.weibo.getPublicTimeline();
            for(final Status status:publicTimeline){
                weiboStatus.add(new SinaWeiboStatus(status));
            }
            return weiboStatus;
        } catch (WeiboException e) {
            throw new WeiboClientException(e.getMessage(), e);
        }
    }
    @Override
    public List<WeiboUser> getRandomUsers() throws WeiboClientException {
    	List<WeiboUser> weiboUserList = new ArrayList<WeiboUser>();
    	try {
    		final List<Status> publicTimeline = this.weibo.getPublicTimeline();
    		List<String> weiboUserIdList = new ArrayList<String>();
    		for(final Status status:publicTimeline){
    			User wbuser = status.getUser();
    			if(!weiboUserIdList.contains(wbuser.getId())){
    				weiboUserList.add(new SinaWeiboUser(wbuser));
    				weiboUserIdList.add(String.valueOf(wbuser.getId()));
    			}
    		}
    		return weiboUserList;
    	} catch (WeiboException e) {
    		throw new WeiboClientException(e.getMessage(), e);
    	}
    }

    @Override
    public WeiboUser getUser(String id) throws WeiboClientException {
        try {
            return new SinaWeiboUser(this.weibo.showUser(id));
        } catch (WeiboException e) {
            throw new WeiboClientException(e.getMessage(), e);
        }
    }
}
